package grisar.gris.helpers;

import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.Bitmap;

/**
 * Resource Allocator,
 * 
 * avoid possible memory leaks by allowing users to store the loaded image here.
 * 
 * TODO: Is this class really needed or does the android framework take care of this?
 * 
 * Options: getFromBuffer true or false, false will skip the storing and just return 
 * the image!
 * 
 * @author kristian
 * 
 */
public class ResourceAllocator {
	
	private static Map<Integer, Bitmap> keeper = new HashMap<Integer, Bitmap>();
	private static Context context;
	
	/**
	 * Has to be called
	 */
	public static void registerContext( Context c ) {
		
		context = c;
	}
	
	/**
	 * Returns the 
	 * 
	 * @param c
	 * @param address
	 * @param getFromBuffer
	 * @return
	 */
	public static Bitmap getDrawable( int address, boolean getFromBuffer ) {
		
		//If user doesn't want to use the save functionality, quit early
		if( !getFromBuffer ) {
			
			BitmapDrawable bd = (BitmapDrawable) (context.getResources().getDrawable(address)); 
			
			return bd.getBitmap();
		}
		
		//If user wants to get the image from our map of saved buffers
		if( getFromBuffer ) {
			
			//If image is already saved, just serve it
			if( keeper.containsKey( address ) ) {
				
				return keeper.get( address );
			
			//If not saved, save and serve!
			} else {
				
				BitmapDrawable bd = (BitmapDrawable) (context.getResources().getDrawable(address));
				
				keeper.put( address, bd.getBitmap() );
				
				return bd.getBitmap();
			}
		}
		
		//This will never be reached as all other branches above returns something.
		return null;
	}
}